﻿using System;
using Caliburn.Micro;
using MediaOwl.WebSearch.TranslatorService;

namespace MediaOwl.WebSearch.Data.Translation
{
    public class Speak : IResult
    {
        private readonly string text;
        private readonly string language;
        private readonly Action<string> onSuccess;
        private readonly Action<Exception> onFail;
        private readonly LanguageServiceClient svcClient;

        public Speak(string text, string language, Action<string> onSuccess, Action<Exception> onFail = null)
        {
            this.text = text;
            this.language = language;
            this.onFail = onFail;
            this.onSuccess = onSuccess;
            svcClient = new LanguageServiceClient();
        }

        public void Execute(ActionExecutionContext context)
        {
            svcClient.SpeakCompleted += (s, e) =>
                                            {
                                                if (e.Error == null)
                                                {
                                                    if (onSuccess != null)
                                                        Caliburn.Micro.Execute.OnUIThread(() => onSuccess(e.Result));
                                                }
                                                else
                                                {
                                                    if (onFail != null)
                                                        Caliburn.Micro.Execute.OnUIThread(() => onFail(e.Error));
                                                }
                                                Completed(this, new ResultCompletionEventArgs{Error = e.Error});
                                            };

            svcClient.SpeakAsync(BingDataAccess.AppId, text, language, "audio/wav");
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}